<?php

class Follower_BD {
	
	// Méthode followed($id_user1,$id_user2) : regare si A suit B. Renvoit un booleen
	public static function AFollowB($id_user1,$id_user2){
	  	$db = Outils_Bd::getInstance()->getConnexion();
	  	$sth=$db->prepare("SELECT count(*) as totalItems FROM Follower WHERE id_user_subject=:id_user1 AND id_user_object=:id_user2");
		$data= array('id_user1' => $id_user1, 'id_user2' => $id_user2);
	  	$sth->execute($data);
	  	$ligne = $sth->fetch(PDO::FETCH_ASSOC);
	 	if ($ligne['totalItems'] > 0)
			return true;
		else
			return false;
	}
		
	// Méthode addFollower($id_user1,$id_user2)
	public static function addFollower($id_user1,$id_user2){
		$db = Outils_Bd::getInstance()->getConnexion();
		$sth=$db->prepare("INSERT INTO Follower ( id_user_subject, id_user_object, time ) VALUES ( :id_user1, :id_user2, :time )");
		$data = array('id_user1' => $id_user1, 'id_user2' => $id_user2,'time' => date("Y-m-d H:i:s"));
		$sth->execute($data);
	}
	
	/* Méthode getFollowedUsers($clause) :  retourne un tableau d'objets User */
	public static function getFollowedUsers($clause,$data=array()){
		$db = Outils_Bd::getInstance()->getConnexion();
		
		$requete = "SELECT User.* FROM Follower INNER JOIN User ON id_user=id_user_object WHERE {$clause}";
		
		if (isset($data['offset'])) {
			$requete .=	" LIMIT {$data['offset']}, {$data['itemsPerPage']}";
			unset($data['offset']);
			unset($data['itemsPerPage']);
		}
		
		$sth=$db->prepare($requete);
		$sth->execute();
		$liste = array();
		while (($ligne = $sth->fetch(PDO::FETCH_ASSOC)) !== false) {
		  	// ajouter un objet User dans le tableau
		  	$liste[] = new User($ligne);
		}
		return $liste;
	}
	
	// Methode count
    public static function count($clause="1=1", $data=array()) {
		
	  	$db = Outils_Bd::getInstance()->getConnexion();
	  	$sth=$db->prepare("SELECT count(*) as totalItems FROM Follower INNER JOIN User ON id_user=id_user_object WHERE {$clause}");
	  	$sth->execute($data);
	  	$ligne = $sth->fetch(PDO::FETCH_ASSOC);
	 	return $ligne['totalItems'];
  }	

}

?>